package com.blacktry.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 删除缓存
     *
     * @param key
     */
    public void delete(String key) {
        this.redisTemplate.delete(key);
    }

    /**
     * 添加ip到缓存
     *
     * @param key
     * @param value
     * @return
     */
    public Long add(String key, String value) {
        return this.redisTemplate.opsForHyperLogLog().add(key, value);
    }

    /**
     * 获取总数
     *
     * @param key
     * @return
     */
    public Long size(String key) {
        return this.redisTemplate.opsForHyperLogLog().size(key);
    }

    /**
     * 获取全部的指定key
     *
     * @return
     */
    public Set<String> getKeys(String pattern) {
        return this.redisTemplate.keys(pattern);
    }

    /**
     * 是否存在key
     * @param key
     * @return
     */
    public boolean isExist(String key) {
        return this.redisTemplate.hasKey(key);
    }

    /**
     * 设置String 类型值
     * @param key
     * @param value
     */
    public void setStringValue(String key, String value){
        this.redisTemplate.opsForValue().set(key,value);
    }

    /**
     * 设置String 类型值，并设置超时时间
     * @param key
     * @param value
     */
    public void setStringValueAndTime(String key, String value, Long time){
        this.redisTemplate.opsForValue().set(key,value,time, TimeUnit.SECONDS);
    }
    /**
     * 获取string 类型 value
     * @param key
     * @return
     */
    public String getStringValue(String key){
        return (String)this.redisTemplate.opsForValue().get(key);
    }
}